<template>
  <div>
    <div class="toptop">
      <div>
        <span>
          <span style="margin-right: 24px;">公司</span>
          <el-select v-model="companyId" placeholder="请选择">
            <el-option v-for="(item, index) in companylist" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </span>
      </div>
      <el-button size="small" class="bottom_all" @click="saveBind()">保存</el-button>
    </div>
    <div class="info" style="display: flex;">
      <div class="left">
        <div class="nav">
          <template v-for="(item, index) in leftList">
            <div :key="index" :style="'width:' + 100 / leftList.length + '%'" :class="item.value == leftIndex ? 'left-active' : ''" @click="changeindex(item.value)">{{ item.text }}</div>
          </template>
        </div>
        <!-- 数据 -->
        <!-- <div class="radio leftitem">
          <el-radio-group v-model="showleftitemId" @change="changeleft(showleftitemId)">
            <template v-for="(item, index) in leftitemList">
              <div :key="index" class="radio-bg">
                <el-radio :label="item.id">{{ item.name }}</el-radio>
              </div>
            </template>
          </el-radio-group>
        </div> -->
        <div class="radio leftitem">
          <div style="padding:10px 0;">
            {{['','原物料名称','强度等级'][leftIndex]}}
            :
          </div> 
          <el-select v-model="showleftitemId" filterable placeholder="请选择" @change="changeRaw">
            <el-option v-for="(item, index) in leftitemList" :key="index" :label="item.name" :value="item.name"></el-option>
          </el-select>
          <div v-show="leftIndex==1">
            <div style="padding:10px 0;">
              规格:
            </div> 
            <el-select v-model="specification" filterable placeholder="请选择" @change="changeleft">
              <el-option v-for="item in specificationList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="center"></div>
      <div class="right">
        <div class="items">
          <div class="item">
            <div class="item-title">检验类别</div>
            <div class="radio">
              <el-radio-group v-model="showtypesId" @change="changetypesId()">
                <template v-for="(item, index) in table.types">
                  <div :key="index" class="radio-bg">
                    <el-radio :label="item.id">
                      <div :class="showtable.some(a => a.qualityDetectionId == item.id) ? 'active' : 'none'"></div>
                      {{ item.name }}
                    </el-radio>
                    <span v-if="showtable.some(a => a.qualityDetectionId == item.id)" class="block">
                      <i class="el-icon-error" style="font-size: 12px;" @click.stop="deleteId(item)"></i>
                    </span>
                  </div>
                </template>
              </el-radio-group>
            </div>
          </div>
          <div class="item-hr"></div>
          <div class="item">
            <div class="item-title">检验项目</div>
            <div style="padding:10px 20px 0">
              <el-input v-model="input" placeholder="模糊查询"></el-input>
            </div>
            <div class="radio">
              <el-checkbox-group v-model="itemId" @change="change1()">
                <template v-for="(item, index) in table.item">
                  <div :key="index" class="radio-bg">
                    <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                  </div>
                </template>
              </el-checkbox-group>
            </div>
          </div>
          <div class="item-hr"></div>
          <div class="item">
            <div class="item-title">检验要求</div>
            <div class="radio">
              <el-checkbox-group v-model="requireId" @change="change1()">
                <template v-for="(item, index) in table.require">
                  <div :key="index" class="radio-bg">
                    <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
                  </div>
                </template>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDicType } from "@/api/common.js";
import { getListByTypeId } from "@/api/common.js";
import {
  setgetList,
  getCategoryBindings,
  saveCategoryBinding,
  deleteCategoryBindings,
  getSpecificatioByName,
} from "@/api/basicConfig/CPYquality.js";
import { permissionsCompanyList } from "@/api/common.js";
export default {
  data() {
    return {
      UserInfo: '',
      leftList: [
        {
          text: "原物料",
          value: 1,
        },
        {
          text: "强度等级",
          value: 2,
        },
      ],
      leftIndex: 1,
      companylist: [],
      companyId: "",
      leftitemList: [],
      leftitemId: "",
      showleftitemId: "",
      table: [],
      showtable: [],
      showtypesId: "",
      typesId: "",
      itemId: [],
      requireId: [],
      loading: false,
      oldirequire: [],
      olditem: [],
      dataType: 1,
      input: '',
      itemList: [],
      specification: '',
      specificationList: [],
      rawId: '',
    };
  },
  watch: {
    dataType: {
      handler() {
        let _this = this
        console.log(JSON.parse(JSON.stringify(this.oldtypes)))
        _this.table.types = _this.oldtypes.filter(res => (res.dataType == _this.dataType))
        _this.table.item = _this.olditem.filter(res => (res.dataType == _this.dataType))
        _this.table.require = _this.oldirequire.filter(res => (res.dataType == _this.dataType))
        _this.itemList = JSON.parse(JSON.stringify(_this.table.item))
      },
      deep: true,
      immediate: false
    },
    leftIndex: {
      handler() {
        let _this = this;
        switch (_this.leftIndex) {
          case 1: {
            getDicType({
              code: "MATname",
            }).then((res) => {
              _this.leftitemList = res.data.items.map((res) => {
                let obj = {
                  id: res.id,
                  name: res.itemName,
                };
                return obj;
              });
              _this.leftitemId = "";
              _this.showleftitemId = "";
              _this.showtypesId = "";
              _this.typesId = "";
              _this.itemId = [];
              _this.requireId = [];
              _this.showtable = [];
            });
            return;
          }
          case 2: {
            getListByTypeId({ typeId: 1 }).then((res) => {
              _this.leftitemId = "";
              _this.showleftitemId = "";
              _this.showtypesId = "";
              _this.typesId = "";
              _this.itemId = [];
              _this.requireId = [];
              _this.showtable = [];
              _this.leftitemList = res.data;
            });
            return;
          }
        }
      },
      deep: false,
      immediate: true,
    },
    companyId() {
      let _this = this;
      _this.getlist();
    },
    leftitemId() {
      let _this = this;
      if (_this.leftitemId) {
        _this.getlist();
      }
    },
    input() {
      this.table.item = new Array();
      if (this.input == '') {
        this.table.item = this.itemList;
      } else {
        this.itemList.forEach(item => {
          if (item.name.indexOf(this.input) !== -1) {
            this.table.item.push(item);
          }
        });
      }
    },
  },
  async created() {
    this.companylist = await permissionsCompanyList()
    this.companyId = this.companylist[0].id
    this.init();
  },
  methods: {
    changeRaw () {
      this.specification = '';
      this.rawId = this.leftitemList.find(item => item.name === this.showleftitemId).id;
      getSpecificatioByName({name: this.showleftitemId}).then(res => {
        if (res.code === 1001) {
          this.specificationList = res.data;
        }
      })
      if (this.leftIndex === 2) {
        this.getlist();
      } 
    },
    change1() {
      if (!this.showtypesId || !this.showleftitemId) {
        this.$message({
          message: "请先选择物料和检验类别",
          type: "warning",
        });
        this.itemId = [];
        this.requireId = [];
        return;
      }
      console.log(this.requireId);
      this.loading = true;
    },
    /*数据保存提示*/
    changeleft() {
      let _this = this;
      if (this.companyId == "") {
        this.$message({
          message: "请选择公司",
          type: "warning",
        });
        return;
      }
      if (_this.loading) {
        _this
          .$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            cancelButtonClass: "bottom_all_two",
            confirmButtonClass: "bottom_all",
            type: "warning",
          })
          .then(() => {
            _this.showleftitemId = _this.leftitemId;
            _this.saveBind();
          })
          .catch(() => {
            _this.leftitemId = _this.specification;
            _this.loading = false;
          });
        return;
      }
      _this.leftitemId = _this.specification;
    },
    changetypesId() {
      let _this = this;
      if (this.companyId == "") {
        this.$message({
          message: "请选择公司",
          type: "warning",
        });
        return;
      }
      if (_this.loading) {
        this.$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            _this.showtypesId = _this.typesId;
            _this.saveBind();
          })
          .catch(() => {
            _this.typesId = _this.showtypesId;
            _this.getendlist();
            _this.loading = false;
          });
        return;
      }
      _this.typesId = _this.showtypesId;
      _this.getendlist();
    },
    changeindex(a) {
      console.log(a);
      this.dataType = a
      let _this = this;
      if (this.companyId == "") {
        this.$message({
          message: "请选择公司",
          type: "warning",
        });
        return;
      }
      if (_this.loading) {
        this.$confirm("请保存更改数据,否则数据将会丢失?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            this.table.types = this.oldtypes.filter(
              (res) => res.dataType == this.leftIndex
            );
            this.table.item = this.olditem.filter(res => (res.dataType == _this.dataType))
            this.table.require = this.oldirequire.filter(res => (res.dataType == _this.dataType))
            _this.saveBind();
          })
          .catch(() => {
            _this.leftIndex = a;
            this.table.types = this.oldtypes.filter(
              (res) => res.dataType == this.leftIndex
            );
            _this.loading = false;
          });
        return;
      }
      _this.leftIndex = a;
      this.table.types = this.oldtypes.filter(
        (res) => res.dataType == this.leftIndex
      );
    },
    init() {
      setgetList().then((res) => {
        this.table = res.data;
        this.olditem = res.data.item
        this.oldirequire = res.data.require
        this.oldtypes = res.data.types;
        this.table.types = this.oldtypes.filter(
          (res) => res.dataType == this.leftIndex
        );
        this.table.item = this.olditem.filter(res => (res.dataType == this.dataType));
        this.itemList = JSON.parse(JSON.stringify(this.table.item))
        this.table.require = this.oldirequire.filter(res => (res.dataType == this.dataType))
      });
    },
    /*获取检验类型*/
    getlist() {
      this.showtypesId = '';
      this.typesId = "";
      this.itemId = [];
      this.requireId = [];
      let data = {
        companyId: this.companyId,
        rawId: this.rawId,
        type: this.leftIndex,
        specification: this.specification,
      };
      if (this.leftIndex == 2) {
        data = {
          companyId: this.companyId,
          strengthGradeId: this.rawId,
          type: this.leftIndex,
        };
      }
      getCategoryBindings(data).then((res) => {
        this.showtable = res.data;
        this.loading = false;
      });
    },
    /*获取多选框*/
    getendlist() {
      if (this.showtable.some((a) => a.qualityDetectionId == this.typesId)) {
        let arr = this.showtable.find(
          (res) => res.qualityDetectionId == this.typesId
        );
        this.itemId = arr.bpList.map((res) => {
          return res.bindingProjectId;
        });
        this.requireId = arr.bcList.map((res) => {
          return res.claimId;
        });
      } else {
        this.itemId = [];
      }
    },
    deleteId(item) {
      this.$confirm("此操作将永久删除该绑定信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        cancelButtonClass: "bottom_all_two",
        confirmButtonClass: "bottom_all",
        type: "warning",
      })
        .then(() => {
          let arr = this.showtable.find(
            (res) => res.qualityDetectionId == item.id
          );
          deleteCategoryBindings({ id: arr.id }).then(() => {
            this.getlist();
          });
        })
        .catch(() => { });
    },
    saveBind() {
      if (this.companyId == "") {
        this.$message({
          message: "请选择公司",
          type: "warning",
        });
        return;
      }
      /**验证：如选择原物料+批次、混凝土+出场（就必选控制标准）------开始 */
      // console.log(this.leftIndex, '原物料、强度等级');//原物料1，强度等级2【判断用不上这个】
      // console.log(JSON.parse(JSON.stringify(this.table.types)), '检验类别数组')
      // console.log(this.showtypesId, '检验类别');//批次对应2，出场对应5
      // console.log(JSON.parse(JSON.stringify(this.table.item)), '检验项目数组')
      // console.log(this.itemId, '检验项目');//检验项目id对应[project1,project2,project3]
      // console.log(JSON.parse(JSON.stringify(this.table.require)), '控制标准数组')
      // console.log(this.requireId, '控制标准');//批次控制标准id对应request2，出场控制标准id对应request1
      if (this.showtypesId == 2 && this.requireId.findIndex((res) => res == 'request2') == -1) {
        //批次
        this.$message({
          message: "检验要求必选：技术要求",
          type: "warning",
        });
        return
      } else if (this.showtypesId == 5) {
        //出场
        console.log(this.itemId.findIndex((res) => res == 'project3') == -1);
        if (this.itemId.findIndex((res) => res == 'project1') == -1 || this.itemId.findIndex((res) => res == 'project2') == -1 || this.itemId.findIndex((res) => res == 'project3') == -1) {
          this.$message({
            message: "检验项目必选：破坏荷载1、破坏荷载2、破坏荷载3",
            type: "warning",
          });
          return
        }
        if (this.requireId.findIndex((res) => res == 'request1') == -1) {
          this.$message({
            message: "检验要求必选：控制标准",
            type: "warning",
          });
          return
        }
      }
      /**验证：如选择原物料+批次、混凝土+出场（就必选控制标准）------结束 */
      let obj = new Object();
      if (this.leftIndex == 1) {
        obj.rawId = this.rawId;
        obj.specification = this.specification;
      } else {
        obj.strengthGradeId = this.rawId;
      }
      obj.companyId = this.companyId;
      obj.type = this.leftIndex;
      obj.qualityDetectionId = this.typesId;
      if (!this.showtable.some((a) => a.qualityDetectionId == this.typesId)) {
        obj.types = 1;
        obj.bpList = this.itemId.map((res) => {
          let a = new Object();
          a.type = 1;
          a.specification = this.specification;
          a.bindingProjectId = res;
          return a;
        });
        obj.bcList = this.requireId.map((res) => {
          let a = new Object();
          a.type = 1;
          a.specification = this.specification;
          a.claimId = res;
          return a;
        });
      } else {
        let arr = this.showtable.find(
          (res) => res.qualityDetectionId == this.typesId
        );
        obj.types = 2;
        obj.id = arr.id;
        let BpallData = arr.bpList.filter((item) =>
          this.itemId.some((items) => item.bindingProjectId == items)
        );
        let BcallData = arr.bcList.filter((item) =>
          this.requireId.some((items) => item.claimId == items)
        );
        let deleteBpData = arr.bpList.filter(
          (item) =>
            !BpallData.some(
              (items) => item.bindingProjectId == items.bindingProjectId
            )
        );
        let deleteBcData = arr.bcList.filter(
          (item) => !BcallData.some((items) => item.claimId == items.claimId)
        );
        let addBpData = this.itemId.filter(
          (item) => !BpallData.some((items) => item == items.bindingProjectId)
        );
        let addBcData = this.requireId.filter(
          (item) => !BcallData.some((items) => item == items.claimId)
        );
        /*修改*/
        BpallData = BpallData.map((res) => {
          let b = new Object();
          b.id = res.id;
          b.type = 2;
          b.specification = this.specification;
          b.bindingProjectId = res.bindingProjectId;
          return b;
        });
        BcallData = BcallData.map((res) => {
          let b = new Object();
          b.id = res.id;
          b.type = 2;
          b.specification = this.specification;
          b.claimId = res.claimId;
          return b;
        });
        /*删除*/
        deleteBpData = deleteBpData.map((res) => {
          let b = new Object();
          b.id = res.id;
          b.type = 0;
          b.specification = this.specification;
          b.bindingProjectId = res.bindingProjectId;
          return b;
        });
        deleteBcData = deleteBcData.map((res) => {
          let b = new Object();
          b.id = res.id;
          b.type = 0;
          b.specification = this.specification;
          b.claimId = res.claimId;
          return b;
        });
        /*添加*/
        addBpData = addBpData.map((res) => {
          let b = new Object();
          b.type = 1;
          b.specification = this.specification;
          b.bindingProjectId = res;
          return b;
        });
        addBcData = addBcData.map((res) => {
          let b = new Object();
          b.type = 1;
          b.specification = this.specification;
          b.claimId = res;
          return b;
        });
        obj.bpList = [...BpallData, ...deleteBpData, ...addBpData];
        obj.bcList = [...BcallData, ...deleteBcData, ...addBcData];
      }
      let datarr = new Array();
      datarr.push(obj);
      saveCategoryBinding(datarr).then((res) => {
        if (res.code == 1001) {
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.getlist();
        }
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.radio-bg:hover .block {
  display: inline-block;
}
.block {
  display: none;
}
.active {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: red;
  margin: 0 5px;
}
.none {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin: 0 5px;
  background: #808080;
}
.toptop {
  padding: 20px 20px 0 20px;
  @include discen_al;
  justify-content: space-between;
}
.info {
  height: 705px;
  padding: 20px;
}
.items {
  display: flex;
  height: 100%;
}
.item {
  flex: 1;
  border: 1px solid rgba(225, 229, 237, 1);
  border-radius: 4px;
  .item-title {
    color: #000000;
    background: #e1e5ed;
    font-size: 14px;
    @include discen;
    height: 56px;
    font-weight: bold;
  }
}
.el-radio {
  margin-right: 5px;
}
.radio {
  padding: 20px;
  .radio-bg {
    height: 28px;
  }
  i {
    color: #808080;
    margin-left: 5px;
  }
  i:hover {
    color: $bg_color;
  }
}
.item-hr {
  width: 20px;
  height: 20px;
}
.center {
  width: 24px;
  height: 100%;
}
.left {
  border: 1px solid rgba(225, 229, 237, 1);
  flex: 2;
  border-radius: 4px;
}
.right {
  flex: 5;
  border-radius: 4px;
}
.nav {
  padding: 0 20px;
  height: 56px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  background: #e1e5ed;
  color: #000000;
  > div {
    font-size: 12px;
    font-weight: bold;
    height: 48px;
    //width: 50%;
    @include discen;
    cursor: pointer;
  }

  .left-active {
    color: $bg_color;
    border-radius: 8px 8px 0px 0px;
    background: #ffffff;
  }
}
.tabtop {
  width: 761px;
}
.radio {
  overflow: auto;
  padding: 20px;
  height: calc(100% - 110px);
  .radio-bg {
    height: 28px;
  }
}
.radio::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}
.radio::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.radio::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
.radio::-webkit-scrollbar-thumb:hover {
  background: $bg_color;
}
.radio::-webkit-scrollbar-corner {
  background: $bg_color;
}
</style>
